package com.rzico.sbl.ui.statistic

import android.widget.ImageView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityGoodsRecordBinding
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class GoodsRecordActivity : BaseActivity(R.layout.activity_goods_record) {

    private val mBinding by lazy { ActivityGoodsRecordBinding.bind(getRootView()) }

    override fun getViewModel() = get<StatisticCommonViewModel>()

    private lateinit var mDateMode: String
    private lateinit var mBeginDate: String
    private lateinit var mEndDate: String

    override fun initData() {
        initTitle(title = "订单列表")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyImg.setEmptyImage(
                    resId = R.mipmap.icon_order_no,
                    dpSize = 100f
                )
                it.emptyHint.text = "暂无相关订单信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderHeader>(R.layout.item_statistic_order_title) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_time, bean.hint + bean.time)
                            text(R.id.item_order_status, bean.status_hint)

                            clicked {
                                startActivityEx<OrderDetailActivity>("orderSn" to bean.orderSN)
                            }
                        }
                    }
                    .register<OrderGoods>(R.layout.item_statistic_order_content) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_title, "${bean.consignee}  ${bean.phone}")
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_price, "单价：${bean.price.formatDecimal()} 元")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            clicked {
                                startActivityEx<OrderDetailActivity>("orderSn" to bean.orderSN)
                            }
                        }
                    }
                    .register<OrderFooter>(R.layout.item_statistic_order_foot) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_count, "共 ${bean.total_num} 件商品")
                            text(R.id.item_order_total, bean.amount.formatDecimal())

                            clicked {
                                startActivityEx<OrderDetailActivity>("orderSn" to bean.orderSN)
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    override fun initListener() {
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        // 今日、昨日、本周、本月、上月、本年、自定义
        mBinding.apply {
            when (mDateMode) {
                "2" -> {
                    recordTime.timeHint.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }

                "3" -> {
                    recordTime.timeHint.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }

                "4" -> {
                    recordTime.timeHint.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }

                "5" -> {
                    recordTime.timeHint.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }

                "6" -> {
                    recordTime.timeHint.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }

                "7" -> {
                    recordTime.timeHint.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }

                else -> {
                    mBeginDate = getTodayDate()
                    mEndDate = getTodayDate()

                    recordTime.timeHint.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }
            }
        }

        mBinding
            .recordTime
            .apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }
    }

    /**
     * 商品订单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodRecord(
                page = index,
                product = intent.getExtra("productId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { total, data ->
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(data)
                        data.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    mBinding
                        .recordTotal
                        .text = total.toString()
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}